<template>
    <div class="order flex">
        <!-- 公共侧边栏 -->
        <Aside></Aside>
        <div style="width: 100%;">
            <!-- 公共导航栏 -->
            <Nav @confirmPermission="confirmPermission"></Nav>
            <div class="bodybox flex">
                <!-- 销售单左边 -->
                <div v-if="radio1 === '1'" :class="store.state ? 'left ml-10  w476 ' : 'left ml-10  w336'">
                    <!-- 销售单列表 -->
                    <SalesOrderlist :orderList="orderList" @change="change" @getorder="getorder"
                        @refreshOrderList="refreshOrderList" />

                    <!-- 销售单曲线图 -->
                    <SalesChart ref="purchaseChart1" />
                </div>
                <!--采购单左边 -->
                <div v-if="radio1 === '2'" :class="store.state ? 'left ml-10  w476 ' : 'left ml-10  w336'">
                    <PurchaseTakelist :purchaseordertesk_id="purchaseordertesk_id * 1"
                        :purcharseTakeList="purcharseTakeList" @change="change" @getPurTake="getPurTake"
                        @refreshPurTakeList="refreshPurTakeList" />
                    <PurchaseOrderlist @getPurOrderID="getPurOrderID" @getPurchaseOrderList1="getPurchaseOrderList1"
                        :purchaseorder_id="purchaseorder_id" :purchaseOrderDetailList="purchaseOrderDetailList" />
                </div>
                <!-- 销售单中间 -->
                <div class="center">
                    <div :class="state ? 'flex aic w754 mb-10' : 'flex aic w1034  mb-10'">
                        <!-- 公共 -->
                        <el-radio-group v-model="radio1" class="ml-4">
                            <!-- 销售单 -->
                            <el-radio label="1" size="large" :disabled="store.type == 3 ? true : false"> Sales Order
                            </el-radio>
                            <!-- 采购单 -->
                            <el-radio label="2" size="large"
                                :disabled="store.type == 2 || store.type == 4 ? true : false">
                                Purchase Order
                            </el-radio>
                        </el-radio-group>
                        <!-- 销售单号 -->
                        <div v-if="radio1 === '1'" class="flex aic ml-20">
                            <span class="f16" style="font-weight:bold;">{{ orderTitle }}</span>
                            <span class="f12 ml-20">{{ CreateTime }}</span>
                        </div>
                        <!-- 采购单号 -->
                        <div v-if="radio1 === '2'" class="flex aic ml-20">
                            <span class="f16" style="font-weight:bold;">{{ purTitle }}</span>
                            <span class="f12 ml-20">{{ purTime }}</span>
                        </div>
                    </div>
                    <!-- 中间头部地址选择开始 -->
                    <div v-if="radio1 === '1'" :class="state ? 'choose flex jc-sb w754' : 'choose flex jc-sb w1034'">
                        <div class="choosebox ">
                            <div class="item">
                                <span class="f14 mr-5 color">Supplier:</span>
                                <el-select v-model="suppierValue" @change="supInfo" @focus="getSuppier"
                                    style="border: none;" class="m-2" size="small" placeholder="Please select Supplier">
                                    <el-option v-for="item in supplierList" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                                <br>
                                <span class="f14 color">Address:</span>
                                <span class="f12 linh color"> {{ suppierInfo }}</span>
                            </div>
                            <div class="item">
                                <span class="f14 mr-5 color">Payment:</span>
                                <el-select v-model="paymentvalue" @change="paymentinfo" @focus="getPayment"
                                    style="border: none;" class="m-2" size="small" placeholder="Please select bank">
                                    <el-option v-for="item in paymentList" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                                <p class="f12 linh color warp">{{ payinfo }}</p>

                            </div>
                        </div>
                        <div class="choosebox ">
                            <div class="item">
                                <span class="f14 mr-5 color">Client:</span>
                                <el-select v-model="userValue" @change="userinfo" @focus="getUser" style="border: none;"
                                    class="m-2" size="small" placeholder="Please select Client">
                                    <el-option v-for="item in userList" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                                <br>
                                <span class="f14 color">Address:</span>
                                <span class="f12 linh color">{{ userAddress }}</span>
                            </div>
                            <div class="item">
                                <span class="f14 color">Delivery Address:</span>
                                <p class="f12 linh color">{{ suppierInfo }}</p>
                                <p class="f12 linh color">{{ userAddress }} </p>
                            </div>
                        </div>
                    </div>

                    <!-- 销售单新建部分按钮开始 -->
                    <div v-if="radio1 === '1'">
                        <div>
                            <div class="sorderproducts mt-20">
                                <div class="flex">
                                    <el-button plain size="small" style="color: #6193D2;border:1px solid #6193D2;"
                                        @click="open(1)">New</el-button>
                                    <el-button type="success" plain size="small"
                                        style="background-color:#ECF5FF;color: #6193D2;border:1px solid #6193D2"
                                        @click="open(6)">Save</el-button>
                                    <el-button type="primary" plain size="small"
                                        style="background-color:#ECF5FF;color: #6193D2;border:1px solid #6193D2"
                                        @click="open(2)">Copy to Order</el-button>
                                    <el-button type="primary" plain size="small"
                                        style="background-color:#ECF5FF;color: #6193D2;border:1px solid #6193D2"
                                        @click="open(3)">From RFQ</el-button>
                                    <el-button type="primary" plain size="small"
                                        style="background-color:#ECF5FF;color: #6193D2;border:1px solid #6193D2"
                                        @click="open(4)">From Quotation</el-button>
                                    <el-button type="primary" plain size="small"
                                        style="background-color:#ECF5FF;color: #6193D2;border:1px solid #6193D2"
                                        @click="open(5)">Clearance</el-button>
                                    <el-button type="danger" style="background-color:#6193D2;color: #fff;border: none;"
                                        plain size="small" @click="orderDelete()">Delete</el-button>
                                </div>

                            </div>
                            <div
                                :class="state ? 'sorderproducts mt-10 flex  w754 jc-sb ' : 'sorderproducts mt-10 flex w1034 jc-sb'">
                                <div class="flex">
                                    <el-button type="primary" plain size="small"
                                        style="background-color:#ECF5FF;color: #6193D2;border:1px solid #6193D2"
                                        @click="open(7)">Place an Order</el-button>
                                    <el-button type="primary" plain size="small"
                                        style="background-color:#ECF5FF;color: #6193D2;border:1px solid #6193D2"
                                        @click="open(8)">Deliver Goods</el-button>
                                    <el-button type="danger"
                                        style="background-color:#ECF5FF;color: #6193D2;border:1px solid #6193D2"
                                        @click="open(9)" plain size="small">Export PI</el-button>

                                </div>

                                <div class="flex">
                                    <el-checkbox v-model="checked1" label="Cost" size="small" />
                                    <el-checkbox v-model="checked2" label="Shipping" size="small" />
                                </div>
                            </div>
                        </div>
                        <!-- 销售单产品列表和新建订单列表开始 -->
                        <div>
                            <SalesProductlist v-if="!state1" @deleteProduct="deleteProduct" @getProductID="getProductID"
                                @resetbrand="resetbrand" @resetproduct="resetproduct" @getBrand="getBrand"
                                @getModel="getModel" :conditionList="conditionList" :leadingList="leadingList"
                                :brandList="brandList" :modelList="modelList" :orderDetails="orderDetails"
                                :state="state" />
                            <SalesNeworder v-else @newDeleteProduct="newDeleteProduct" @getqtnid="getqtnid"
                                @resetbrand="resetbrand" @resetproduct="resetproduct" @getBrand="getBrand"
                                @getModel="getModel" @chooseDescr="chooseDescr" :neworderList="neworderList"
                                :conditionList="conditionList" :leadingList="leadingList" :brandList="brandList"
                                :modelList="modelList" :orderDetails="orderDetails" :state="state" />
                        </div>
                    </div>


                    <!-- 采购按钮开始 -->
                    <div v-if="radio1 === '2'">
                        <div :class="state ? 'porderproducts w754 ' : 'porderproducts w1034 '">
                            <div class="flex bd-r" style="background-color: #ffffff;padding:10px;" >
                                <el-button plain size="small" @click="openNewOrder"
                                    style="color: #6193D2;border:1px solid #6193D2;">New</el-button>
                                <el-button type="success" plain size="small"
                                    @click="allocationMethod(allocationState ? 'SaveAllocation' : 'AssignTasks')"
                                    style="background-color:#ECF5FF;color: #6193D2;border:1px solid #6193D2;margin-left: 10px;">{{
                                        allocationState?'SaveAllocation': 'AssignTasks'
                                    }}</el-button>
                                <el-button @click="taskDelete" type="danger" size="small" plain
                                    style="background-color:#6193D2;color: #fff;border: none;margin-left: 10px;">Delete</el-button>


                            </div>
                        </div>
                        <!-- 采购任务详情 -->
                        <div v-if="radio1 === '2'">
                            <PurchaseTakedetail @compare="compare" @returnTask="returnTask" :buyerList="buyerList"
                                :takeDetailList="takeDetailList" :allocationState="allocationState" :state="state" />

                        </div>
                        <!-- 采购列表详情 -->
                        <div :class="state ? 'porderproducts mt-10  w754 bd-r' : 'porderproducts mt-10 w1034 bd-r'">
                            <div class="flex bd-r" style="background-color: #ffffff;padding: 10px;">
                                <el-button type="success" plain size="small"
                                    style="background-color:#ECF5FF;color: #6193D2;border:1px solid #6193D2;margin-left: 10px;">ChangeThePrice</el-button>
                                <el-button type="success" @click="ExportPorder" plain size="small"
                                    style="background-color:#ECF5FF;color: #6193D2;border:1px solid #6193D2;margin-left: 10px;">Export</el-button>
                            </div>

                        </div>
                        <div v-if="radio1 === '2'">
                            <PurchaseOrderdetail :purOrderDetailList="purOrderDetailList" :state="state" />
                        </div>
                    </div>
                    <!-- 销售中间底部开始 -->
                    <div v-if="radio1 === '1'"
                        :class="state ? 'footer mt-20 flex jc-sb w754' : 'footer mt-20 flex jc-sb w1034'">
                        <dl class="footer-left ">
                            <dt v-for="item in paymentRecieved">
                                Payment Received:
                                <span class="f14">{{ utils.currencType(item.Current) }}{{ item.Paied }}{{
                                    item.ReceiveTime
                                }}from {{ item.payment }}</span>
                            </dt>
                            <div class="table">
                                <dd v-for="item in costs" class="f14">
                                    Cost: <span class="f12">{{ utils.currencType('RMB') }}{{ item.price }}</span>
                                </dd>
                                <dd v-for="item in footershippingCost" class="f14">
                                    Shipping Cost:<span class="f12">{{ utils.currencType('RMB') }}{{
                                        item.Shipping_cost
                                    }}</span>
                                </dd>
                            </div>
                        </dl>
                        <div class="footer-right ">
                            <dl class="flex aic">
                                <dd class="color ddtitle cp f14" @click="open1(1)">Discount</dd>
                                <p class="shuxian"></p>
                                <dd class="color ddtitle cp f14" @click="open1(2)">ShippingCost</dd>
                                <p class="shuxian"></p>
                                <dd class="color ddtitle cp f14" @click="open1(3)">PaymentFee</dd>
                                <p class="shuxian"></p>
                                <dd class="color ddtitle cp f14" @click="open1(4)">Vat</dd>
                            </dl>
                            <dl class="table">
                                <dd class="f14">
                                    Subtal: <span class="f12">{{ utils.currencType('USD') }}{{ subTotal }}</span>
                                </dd>
                                <dd class="f14" v-if="discountInfo !== 0">
                                    Discount: <span class="f12">{{ utils.currencType('USD') }}{{ discountInfo }}</span>
                                </dd>
                                <dd class="f14" v-if="shippingCostInfo !== 0">
                                    ShippingCost: <span class="f12">{{ utils.currencType('USD') }}{{
                                        shippingCostInfo
                                    }}</span>
                                </dd>
                                <dd class="f14" v-if="paymentFeeInfo !== 0">
                                    PaymentFee: <span class="f12">{{ utils.currencType('USD') }}{{
                                        paymentFeeInfo
                                    }}</span>
                                </dd>
                                <dd class="f14" v-if="vatInfo !== 0">
                                    Vat: <span class="f12">{{ utils.currencType('USD') }}{{ vatInfo }}</span>
                                </dd>
                                <dd class="f14" v-if="totalInfo !== 0">
                                    Total: <span class="f12">{{ utils.currencType('USD') }}{{ totalInfo }}</span>
                                </dd>
                            </dl>
                        </div>
                    </div>

                </div>
                <!-- 公共右边聊天窗开始 -->
                <div class="right  ml-10 mr-10" v-if="state">
                    <Right :state="state" />
                </div>
            </div>
        </div>
        <!-- 销售单头部弹窗 -->
        <Clearance ref="clearance" @ClearanceSave="ClearanceSave" @getnumber="getnumber" :isrelease="isrelease"
            :declareAmount="declareAmount" :totalAmount="totalAmount" :currentList="currentList"
            :clearList="clearList" />

        <Copy ref="copy" @newOrder="newOrder" @copyOrderSave="copyOrderSave" @copyOrder="copyOrder"
            @SelectionMethod="SelectionMethod" @getorderProductList="getorderProductList" @resetorderid="resetorderid"
            @getOrderid="getOrderid" :order_id="order_id * 1" :orderTitle="orderTitle" :rightOrder="rightOrder"
            :leftOrder="leftOrder" :orderidList="orderidList" />
        <FromQtn ref="fromqtn" @qtnnewOrder="qtnnewOrder" @qtnSave="qtnSave" @qtnAdd="qtnAdd"
            @SelectionMethod="SelectionMethod" @getqtnProductList="getqtnProductList" @resqtnid="resqtnid"
            @getqtnid="getqtnid" :qtnnewList="qtnnewList" :qtnProductList="qtnProductList" :qtnidList="qtnidList"
            :orderidList="orderidList" :order_id="order_id * 1" :orderTitle="orderTitle" @getOrderid="getOrderid"
            @resetorderid="resetorderid" />
        <FromRfq ref="fromrfq" @rfqnewOrder="rfqnewOrder" @rfqSave="rfqSave" @rfqAdd="rfqAdd"
            @SelectionMethod="SelectionMethod" @getrfqProductList="getrfqProductList" @resrfqid="resrfqid"
            @getrfqid="getrfqid" @getOrderid="getOrderid" @resetorderid="resetorderid" :rfqnewList="rfqnewList"
            :rfqProductList="rfqProductList" :rfqidList="rfqidList" :orderidList="orderidList" :order_id="order_id * 1"
            :orderTitle="orderTitle" />
        <ExportPI ref="exportPI" :imgList="imgList" :exportPImodels="exportPImodels" :capitalTotal="capitalTotal"
            :invoiceInfo="invoiceInfo" />
        <PlaceAnOrder ref="placeanOrder" @changeRadio="changeRadio" @purchaseOrderteskAdd="purchaseOrderteskAdd"
            @changePur="changePur" :orderName="orderName" :orderDetails="orderDetails" :buyerList="buyerList" />

        <Delivergoods ref="deliverGoods" :orderName="orderName" />
        <!-- 销售单底部弹窗 -->
        <Discount ref="discount" @discountSave="discountSave" @calculation="calculation" :subTotal="subTotal * 1" />

        <Vat ref="vat" @vatSave="vatSave" @vatcalculation="vatcalculation" :subTotal="subTotal * 1" />

        <ShippingCost ref="shippingCost" @shippingCostSave="shippingCostSave" :subTotal="subTotal * 1" />

        <PaymentFee ref="paymentfee" @paymentFeecompute="paymentFeecompute" @paymentFeeSave="paymentFeeSave"
            :subTotal="subTotal * 1" />
        <!-- 采购弹窗 -->
        <NewPurchaseOrder ref="newPurchaseOrder" @changeNonStock="changeNonStock"
            @CreatePurchaseOrder="CreatePurchaseOrder" @inPmoney="inPmoney" @inputPqty="inputPqty"
            :pSupplierList="pSupplierList" :leadingList="leadingList" :takeDetailList="takeDetailList" />
        <ExportPurOrder ref="exportPurOrder" />
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue"
import { ElMessage, ElMessageBox } from 'element-plus'
// 采购订单组件
import PurchaseTakelist from "./components/PurchaseTakelist.vue"
import PurchaseTakedetail from "./components/PurchaseTakedetail.vue"
import PurchaseOrderlist from "./components/PurchaseOrderlist.vue"
import PurchaseOrderdetail from "./components/PurchaseOrderdetail.vue"

// 采购弹框组件
import NewPurchaseOrder from "./components/PurchaseTopComponents/NewPurchaseOrder.vue"
import ExportPurOrder from "./components/PurchaseTopComponents/ExportPurOrder.vue"
// 销售底部弹框
import ShippingCost from "./components/FooterComponents/ShippingCost.vue"
import PaymentFee from "./components/FooterComponents/PaymentFee.vue"
import Discount from "./components/FooterComponents/Discount.vue"
import Vat from "./components/FooterComponents/Vat.vue"
// 销售订单相关弹框
import Clearance from "./components/TopComponents/Clearance.vue";
import Copy from "./components/TopComponents/Copy.vue";
import FromQtn from "./components/TopComponents/FromQtn.vue";
import FromRfq from "./components/TopComponents/FromRfq.vue";
import ExportPI from "./components/TopComponents/ExportPI.vue";
import PlaceAnOrder from "./components/TopComponents/PlaceAnOrder.vue";
import Delivergoods from "./components/TopComponents/Delivergoods.vue"
// 销售其他组件
import Aside from "../components/Aside.vue"
import Nav from "../components/Nav.vue"
import SalesOrderlist from "./components/SalesOrderlist.vue"
import SalesChart from "./components/SalesChart.vue"
import SalesProductlist from "./components/SalesProductlist.vue"
import SalesNeworder from "./components/SalesNeworder.vue";

// 右侧公共聊天组件
import Right from "./components/Right.vue";
// 相关js方法
import * as api from "../../api1/index"
import * as utils from "./utils.js"
// pinia
import { useDemoStore } from '../../pinia/index'


const store = useDemoStore()

// 顶部单选框
const radio1 = ref()

// 确认权限
const confirmPermission = () => {
    // 销售和客户
    if (store.type == 2 || store.type == 4) {
        radio1.value = '1'
        // 采购
    } else if (store.type == 3 || store.type == 0) {
        radio1.value = '2'
    } else {
        radio1.value = '1'
    }
}
/********************************销售单逻辑开始******************************************** */
// cost shopping复选框
const checked1 = ref(true)
const checked2 = ref(false)
const token = store.token

/**获取供应商开始 */
const suppliers = ref([])
const supplierList = ref([])
const suppierValue = ref('')
const getSuppier = () => {
    api.orderSupplier({ token: token }).then((res) => {
        suppliers.value = res.data
        supplierList.value = res.data.map((item) => {
            let label = item.config_short
            let value = item.config_short
            return {
                label,
                value
            }
        })
    })
}
// 选择供应商后触发
const suppierInfo = ref('')
const company_id = ref('')
const supInfo = (val) => {
    suppierInfo.value = suppliers.value.filter(item => item.config_short === val)[0].config_short
    company_id.value = suppliers.value.filter(item => item.config_short === val)[0].config_id
}
/**获取供应商结束 */

/** 底部支付信息开始 */
const paymentRecieved = ref([])
const costs = ref([])
const footershippingCost = ref([])
const subTotal = ref('')
const discountInfo = ref('')
const shippingCostInfo = ref('')
const paymentFeeInfo = ref('')
const vatInfo = ref('')
const totalInfo = ref('')

/**底部支付信息结束 */

/**获取银行列表开始 */
const paymentList = ref([])
const payments = ref([])
const paymentvalue = ref('')
const bankID = ref('')
// 订单默认银行id
const getPayment = () => {
    const data3 = {
        token: token,
        country_id: 2
    }
    api.orderPayment(data3).then((res) => {
        payments.value = res.data
        paymentList.value = res.data.map((item) => {
            let label = item.bank_name;
            let value = item.bank_name
            return {
                label,
                value
            }
        })
    })
}
// 选择银行后触发
const payinfo = ref('')
const bankName = ref('')
const paymentinfo = (val) => {
    payinfo.value = payments.value.filter(item => item.bank_name === val)[0].bank_info
    bankID.value = payments.value.filter(item => item.bank_name === val)[0].bank_id
    bankName.value = payments.value.filter(item => item.bank_name === val)[0].bank_type
}
/**获取银行列表结束 */


/** 获取用户列表开始*/
const users = ref([])
const userList = ref([])
// 客户选择后展示的内容
const userValue = ref('')
const userdata = {
    token: token,
    kw: '',
    is_supplier: '',
    page: 1
}
const getUser = () => {
    userdata.is_supplier = 0
    api.orderUser(userdata).then((res) => {
        users.value = res.data.data;
        userList.value = res.data.data && res.data.data.map((item) => {
            let label = item.firstname;
            let value = item.customer_info_id;
            return {
                value,
                label
            }
        })
    })
}

// 客户地址
const userAddress = ref('')
// 客户名
const firstName = ref('')
const lastName = ref('')
const usersID = ref('')
// 选择用户后触发
const userinfo = (val) => {
    userAddress.value = users.value.filter(item => item.customer_info_id === val)[0].address
    firstName.value = users.value.filter(item => item.customer_info_id === val)[0].firstname
    lastName.value = users.value.filter(item => item.customer_info_id === val)[0].lastname
    usersID.value = users.value.filter(item => item.customer_info_id === val)[0].customer_info_id
}
/** 获取用户列表结束*/



/**获取订单开始 */
const orderList = ref([])
let data = {
    token: token,
    page: ''
}
const getOrderList = () => {
    data.page = 1
    api.orderList(data).then((res) => {
        orderList.value = res.data.data
        //默认以第一个订单渲染详情
        getorder1();

    })
}
// 上拉加载
const refreshOrderList = () => {
    data.page++
    api.orderList(data).then((res) => {
        orderList.value = [
            ...orderList.value,
            ...res.data.data
        ]
    })

}
// 获取订单详情 
const orderTitle = ref('')
const CreateTime = ref('')
const orderDetails = ref([])
const product_id = ref([])

// 订单id
const order_id = ref('')
const orderName = ref('')
const data1 = {
    token: token,
    order_id: '',
    page: 1,
    is_cost: 1
}
// 点击获取详情
const getorder = (row) => {
    console.log(row)
    if (isclose.value === 2) {
        return false
    }
    data1.order_id = row.order_id
    order_id.value = row.order_id
    orderName.value = row.PI_name
    porderDetails()
}

// 默认订单列表第一条数据详情渲染详情
const getorder1 = () => {
    data1.order_id = orderList.value[0] && orderList.value[0].order_id
    order_id.value = orderList.value[0] && orderList.value[0].order_id
    orderName.value = orderList.value[0] && orderList.value[0].PI_name
    porderDetails()
}

// 获取订单请求赋值
const porderDetails = () => {
    api.orderDetail(data1).then((res) => {
        // 产品列表
        orderDetails.value = res.data.list.data
        // 订单title
        orderTitle.value = res.data.customer.PI_name
        CreateTime.value = res.data.customer.CreateTime
        // 银行信息
        paymentvalue.value = res.data.payment.config_short
        payinfo.value = res.data.payment.config_value
        bankID.value = res.data.payment.config_id
        // 供应商信息
        suppierValue.value = res.data.company.config_short
        suppierInfo.value = res.data.company.config_value
        company_id.value = res.data.company.config_id
        // 客户信息
        userValue.value = res.data.customer.firstname
        userAddress.value = res.data.customer.address
        //底部信息
        paymentRecieved.value = res.data.paymentRecieved
        costs.value = res.data.costs
        footershippingCost.value = res.data.shippingCost
        subTotal.value = res.data.subtal
        discountInfo.value = res.data.customer.discount_value
        shippingCostInfo.value = res.data.customer.Shipping_cost
        paymentFeeInfo.value = res.data.customer.Payment_charge
        vatInfo.value = res.data.customer.Invoice_shipping_cost
        totalInfo.value = res.data.customer.total
        // 第一个订单产品列表的第一个产品
        product_id.value = res.data.list.data[0] && res.data.list.data[0].product_id
        getCurveDiagram()
    })
}
/**获取订单结束 */

/**获取产品曲线数据开始 */
const purchaseChart1 = ref()


const salesList = ref([])
const purchaseList = ref([])
const curveDiagramdata = {
    token: token,
    product_id: ''
}


/*8888888888888888888888888888888888888888888*/
// 默认获取第一个列表第一个产品
const getCurveDiagram = () => {
    curveDiagramdata.product_id = product_id.value
    api.ordersProductRecord(curveDiagramdata).then((res) => {
        purchaseList.value = res.data.purchase
        salesList.value = res.data.sale
        purchaseChart1.value && purchaseChart1.value.init(purchaseList.value, salesList.value)

    })
}
// 点击产品获取
const getProductID = (row) => {
    curveDiagramdata.product_id = row.product_id
    api.ordersProductRecord(curveDiagramdata).then((res) => {
        purchaseList.value = res.data.purchase
        salesList.value = res.data.sale
        purchaseChart1.value && purchaseChart1.value.init(purchaseList.value, salesList.value)

    })
}
/**获取产品曲线数据结束 */
/*8888888888888888888888888888888888888888888*/




/* *搜索获取产品列表开始 */
const modelList = ref([])
const models = ref([])
const data2 = {
    token: token,
    kw: ''
}
// 防抖
let timer;
const getModel = (x) => {
    if (x.data !== null) {
        data2.kw += x.data
    } else {
        data2.kw = data2.kw.slice(0, -1)
    }
    clearTimeout(timer)
    timer = setTimeout(() => {
        api.orderModel(data2).then((res) => {
            models.value = res.data.data
            modelList.value = res.data.data && res.data.data.map((item) => {
                let label = item.model
                let value = item.product_id
                return { label, value }
            })
        })
    }, 100)
}
// 产品框失去焦点后重置输入框
const resetproduct = () => {
    data2.kw = ''
}
/* *搜索获取产品列表结束 */



/* *搜索获取产品品牌列表开始 */
const brandList = ref([])
const biands = ref([])
let timer1
let data3 = {
    token: token,
    kw: ''
}
const getBrand = (x) => {
    if (x.data) {
        data3.kw += x.data
    } else {
        data3.kw = data2.kw.slice(0, -1)
    }
    clearTimeout(timer1)
    timer1 = setTimeout(() => {
        api.orderBrand(data3).then((res) => {
            biands.value = res.data.data
            brandList.value = res.data.data && res.data.data.map((item) => {
                let label = item.brand_name
                let value = item.brand_id
                return { label, value }
            })
        })
    }, 100)

}
// brand框失去焦点重置输入框
const resetbrand = () => {
    data3.kw = ''
}
/* *搜索获取产品品牌列表结束 */

/**获取交期列表开始 */
const leadingList = ref([])
const getleading = () => {
    api.orderLeading({ token: token }).then((res) => {
        leadingList.value = res.data
    })
}
/**获取交期列表结束 */

/**获取货况列表开始 */
const conditionList = ref([])
const getCondition = () => {
    api.orderCondition({ token: token }).then((res) => {
        conditionList.value = res.data
    })
}
/**获取货况列表结束 */

/**编辑订单保存开始 */
const editSave = () => {
    const orderSaves = orderDetails.value.map(item => {
        return {
            "order_info_id": item.order_info_id,
            "product_id": item.product_name_pi.split('|')[1] ? item.product_name_pi.split('|')[1] * 1 : item.product_id,
            "Brand_id": item.Brand_name.split('|')[1] ? item.Brand_name.split('|')[1] * 1 : item.Brand_id,
            "Brand_name": item.Brand_name.split('|')[0],
            "product_description_pi": item.product_name_pi.split('|')[0],
            "product_name_pi": item.product_name_pi.split('|')[0],
            "quantity": item.quantity,
            "price": item.price,
            "leadingtime": item.leadingtime,
            "product_condition": item.product_condition
        }
    })
    const editdata = {
        token: token,
        order_id: order_id.value,
        company_id: company_id.value,
        payment: {
            config_id: bankID.value,
            config_name: bankName.value ? bankName.value : paymentvalue.value
        },
        item: orderSaves
    }
    api.orderEdit(editdata).then((res) => {
        ElMessage({
            type: 'success',
            message: 'Save successfully',
        })
    })
}
/**编辑订单保存结束 */

/**创建订单开始 */
const neworderList = ref([])
const chooseDescr = (product_name_pi) => {
    if (product_name_pi.$index === neworderList.value.length - 1) {
        neworderList.value.push(
            {
                Brand_id: "",
                Brand_name: "",
                cost: "",
                leadingtime: "",
                order_info_id: "",
                price: "",
                product_condition: "",
                product_description_pi: "",
                product_id: "",
                product_name_pi: "",
                profit: "",
                quantity: "",
                related_doc: "",
            }
        )
    }

}

const orderAdd = () => {
    // 恢复默认编辑保存
    issave.value = 1
    const itemList = neworderList.value.map((item) => {
        return {
            "product_id": item.product_name_pi.split('|')[1], //产品ID
            "Brand_id": item.Brand_name.split('|')[1], //品牌ID
            "Brand_name": item.Brand_name.split('|')[0], //品牌名
            "product_description_pi": item.product_name_pi.split('|')[0],
            "product_name_pi": item.product_name_pi.split('|')[0], //产品型号
            "quantity": item.quantity, //订单数量
            "price": item.price, //订单价格
            "leadingtime": item.leadingtime, //交期
            "product_condition": item.product_condition //货况
        }
    })
    const orderData = {
        token: token,
        order: {
            fistname: firstName.value,
            lastname: lastName.value,
            customer_info_id: usersID.value, //客户ID
            company_id: company_id.value, //公司ID
        },
        payment: {
            config_id: bankID.value, //银行ID
            config_name: bankName.value //银行名
        },
        item: itemList
    }
    // 删除最后一条空数据
    orderData.item.pop()
    api.ordersAdd(orderData).then((res) => {
        if (res.Status === 0) {
            ElMessage({
                type: 'success',
                message: 'Successfully created',
            })
            neworderList.value = []
        }
    })

}

// 创建订单删除产品
const newDeleteProduct = (info) => {
    if (neworderList.value.length === 1) {
        ElMessage({
            type: 'info',
            message: "No data can be deleted",
        })
        return false
    }
    neworderList.value.splice(info.$index, 1)
}
/**创建订单结束 */

/**删除订单开始 */
const orderDelete = () => {
    if (isclose.value === 2 || orderList.value.length === 0) {
        ElMessage({
            type: 'info',
            message: "Unable to delete temporarily",
        })
        return false
    }
    const deldata = {
        token: token,
        order_id: order_id.value
    }
    ElMessageBox.confirm(
        'Are you sure to delete this order?',
        'Warning',
        {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            distinguishCancelAndClose: true,
        }
    )
        .then(() => {
            api.orderDelete(deldata).then((res) => {
                if (res.Status === 0) {
                    getOrderList()
                    ElMessage({
                        type: 'success',
                        message: 'Deleted successfully',
                    })
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Deletion failure',
            })
        })
}

/**删除订单结束 */

/**删除订单产品开始 */
const deleteProduct = (operation) => {
    const dpdata = {
        token: token,
        order_info_id: operation.row.order_info_id
    }
    api.orderProductDelete(dpdata).then((res) => {
        if (res.Status === 0) {
            orderDetails.value.splice(operation.$index, 1)
            ElMessage({
                type: 'success',
                message: 'Deleted successfully',
            })
        }
    })
}

/**删除订单产品结束 */


// 重置输入框(弹框部分公用)
const resetorderid = () => {
    data4.kw = ''
}
// 公用复选框方法
const selectList = ref([])
const SelectionMethod = (val) => {
    selectList.value = val
}
/**
 * newOrder 公共方法
 * @param {*确定保存按钮性质} newissave 
 * 1、edit保存，2、new保存,3、cp保存, 4、rfq保存,5、qtn保存
 * @param {*确定新建订单性质是否为弹窗} newstat 
 * 1为直接创建，0为弹框创建
 */
const publicNew = (newissave, newstat) => {
    if (isclose.value === 1) {
        ElMessageBox.confirm(
            'New data will cause data loss. Determine whether to save the data?',
            'Warning',
            {
                confirmButtonText: 'OK',
                cancelButtonText: 'Cancel',
                distinguishCancelAndClose: true,
            }
        )
            .then(() => {
                editSave()
                // 订单title
                orderTitle.value = ""
                CreateTime.value = ""
                // 银行信息
                paymentvalue.value = ""
                payinfo.value = ""
                // 供应商信息
                suppierValue.value = ""
                suppierInfo.value = ""
                // 客户信息
                userValue.value = ""
                userAddress.value = ""
                // 点击新建订单弹窗关闭
                isclose.value = 2
                // 切换为订单新增表格
                state1.value = true

                // 更改保存状态为新建订单保存 1、edit保存，2、new保存,3、cp保存, 4、rfq保存,5、qtn保存
                issave.value = newissave
                // 1创建列表插入一条空数据，0直接赋值
                if (newstat === 1) {
                    // 给创建列表插入一条数据
                    neworderList.value.push(
                        {
                            Brand_id: "",
                            Brand_name: "",
                            cost: "",
                            leadingtime: "",
                            order_info_id: "",
                            price: "",
                            product_condition: "",
                            product_description_pi: "",
                            product_id: "",
                            product_name_pi: "",
                            profit: "",
                            quantity: "",
                            related_doc: "",
                        }
                    )
                } else {
                    // 创建列表重新赋值
                    neworderList.value = selectList.value
                }

            })
            .catch(() => {
                // 点击取消后恢复弹窗
                isclose.value = 1
                ElMessage({
                    type: 'info',
                    message: 'Save cancelled',
                })
            })
    }
}

/**
 * 弹框neworder 公共方法
 * @param {* 创建列表} neworderList 
 * @param {* 组件名} componentName 
 * @param {* 弹框左列表} leftList 
 * @param {* 弹框右列表} rightList 
 * 
 */
const publicNeworder = (neworderList, componentName, leftList, rightList) => {
    const item = neworderList.value.map((item) => {
        return {
            "product_id": item.product_name_pi.split('|').length === 2 ? item.product_name_pi.split('|')[1] * 1 : item.product_id * 1, //产品ID
            "Brand_id": item.Brand_name.split('|').length === 2 ? item.Brand_name.split('|')[1] * 1 : item.Brand_id * 1, //品牌ID
            "Brand_name": item.Brand_name.split('|').length === 2 ? item.Brand_name.split('|')[0] : item.Brand_name, //品牌名
            "product_description_pi": item.product_name_pi.split('|').length === 2 ? item.product_name_pi.split('|')[0] : item.product_name_pi,
            "product_name_pi": item.product_name_pi.split('|').length === 2 ? item.product_name_pi.split('|')[0] : item.product_name_pi, //产品型号
            "quantity": item.quantity, //订单数量
            "price": item.price, //订单价格
            "leadingtime": item.leadingtime, //交期
            "product_condition": item.product_condition //货况
        }
    })
    const NewSavedata = {
        token: token,
        order: {
            fistname: firstName.value,
            lastname: lastName.value,
            customer_info_id: usersID.value, //客户ID
            company_id: company_id.value, //公司ID
            Current: "USD" //货币类型
        },
        payment: {
            config_id: bankID.value, //银行ID
            config_name: bankName.value //银行名
        },
        item: item
    }
    api.ordersAdd(NewSavedata).then((res) => {
        if (res.Status === 0) {
            ElMessage({
                type: 'success',
                message: 'Successfully created',
            })
            // 重置相关内容
            if (componentName.value.rfqID) {
                componentName.value.rfqID = ''
            }
            else if (componentName.value.qtnID) {
                componentName.value.qtnID = ''
            }
            else if (componentName.value.orderID1) {
                componentName.value.orderID1 = ''
            }
            neworderList.value = []
            leftList.value = []
            rightList.value = []
        }
    })
}

/**
 * qtn rfq 保存公共方法 
 * @param {*右侧列表} rightlist 
 * @param {*组件名} componentName 
 * @param {*左侧列表} leftList 
 * @param {*id} id
 */
const publicSave = (rightlist, componentName, leftList, id) => {
    console.log(componentName.value)
    const item = rightlist.value.map((item) => {
        return {
            "order_id": id,
            "inquiry_id": item.inquiry_id ? item.inquiry_id : '0',
            "inquiry_item_purchase_price_id": item.inquiry_item_purchase_price_id ? item.inquiry_item_purchase_price_id : '0',
            "product_id": item.product_id,
            "model": item.product_name_pi,
            "brand_id": item.Brand_id,
            "brand_name": item.Brand_name,
            "product_condition": item.product_condition,
            "quantity": item.quantity,
            "price": item.price,
            "leadingtime": item.leadingtime
        }
    })
    const data = {
        token: store.token,
        isNew: 0,
        order: order,
        item: item
    }
    data.order.quotation_current = 'USD' //币种
    api.orderFromRfqSave(data).then((res) => {
        if (res.Status === 0) {
            if (componentName.value.rfqID) {
                componentName.value.rfqID = ''
            }
            else if (componentName.value.qtnID) {
                componentName.value.qtnID = ''
            }
            componentName.value.open = false
            leftList.value = []
            rightlist.value = []
            ElMessage({
                type: 'success',
                message: 'Successful replication',
            })
        }

    })
}
/*** 重置方法*/
const resetMethod = () => {
    // 保存后，恢复订单产品表格
    state1.value = false
    // 恢复新建弹窗功能
    isclose.value = 1
}

/**订单相关的弹窗开始 */
const clearance = ref()
const copy = ref()
const fromrfq = ref()
const fromqtn = ref()
const exportPI = ref()
const placeanOrder = ref()
const deliverGoods = ref()
// 切换新增订单
const state1 = ref(false)
// 控制产品列表大小
const state = ref(true)
const change = () => {
    state.value = !state.value

}
// 控制新建弹窗是否开启，设置点击后再次点击不在弹窗
let isclose = ref(1)
// 做判断 默认1为订单编辑保存
let issave = ref(1)
const open = (x) => {
    if (x === 1) {
        publicNew(2, 1)
    }
    // copy to order
    else if (x === 2) {
        if (isclose.value === 2) {
            ElMessage({
                type: 'info',
                message: "New order cannot use popover",
            })
            return false
        }
        copy.value.dialogopen()
    }
    // from rfq
    else if (x === 3) {
        if (isclose.value === 2) {
            ElMessage({
                type: 'info',
                message: "New order cannot use popover",
            })
            return false
        }
        fromrfq.value.dialogopen()
    }
    // fromqtn
    else if (x === 4) {
        if (isclose.value === 2) {
            ElMessage({
                type: 'info',
                message: "New order cannot use popover",
            })
            return false
        }
        fromqtn.value.dialogopen()
    }
    // clearance
    else if (x === 5) {
        if (isclose.value === 2) {
            ElMessage({
                type: 'info',
                message: "New order cannot use popover",
            })
            return false
        }
        clearance.value.dialogopen()
        getClearList()
    }
    // placeAnOrder
    else if (x === 7) {
        if (isclose.value === 2) {
            ElMessage({
                type: 'info',
                message: "New order cannot use popover",
            })
        }
        placeanOrder.value.dialogopen()
        getOrderedList()
        getBuyerList()

    }
    // DeliverGoods
    else if (x === 8) {
        if (isclose.value === 2) {
            ElMessage({
                type: 'info',
                message: "New order cannot use popover",
            })
        }
        deliverGoods.value.dialogopen()
    }
    // export PI
    else if (x === 9) {
        if (isclose.value === 2) {
            ElMessage({
                type: 'info',
                message: "New order cannot use popover",
            })
            return false
        }
        exportPI.value.dialogopen()
        getExportPI()
    }
    // save
    else if (x === 6) {
        // 订单编辑保存
        if (issave.value === 1) {
            if (orderList.value.length === 0) {
                ElMessage({
                    type: 'info',
                    message: "No data, can't save",
                })
                return false
            }
            alert('编辑保存')
            editSave()
        }
        // 新建订单
        else if (issave.value === 2) {
            alert('新建订单')
            orderAdd()
            resetMethod()
            setTimeout(() => { getOrderList() }, 500)

        }
        // copy to order 新建订单保存
        else if (issave.value === 3) {
            alert('copy to order')
            copyNeworderSave()
            resetMethod()
            setTimeout(() => { getOrderList() }, 500)
        }
        // from rfq
        else if (issave.value === 4) {
            alert('from rfq ')
            rfqneworderSave()
            resetMethod()
            setTimeout(() => { getOrderList() }, 500)
        }
        // from qtn
        else if (issave.value === 5) {
            alert('from qtn ')
            qtnneworderSave()
            resetMethod()
            setTimeout(() => { getOrderList() }, 500)
        }
    }

}
/**订单相关的弹窗结束 */
let timer2
const data4 = {
    token: token,
    kw: ''
}
// 订单来源的弹窗orderID列表公用
const orderidList = ref([])
// 搜索订单id列表，弹窗公用
const getOrderid = (x) => {
    if (x.data !== null) {
        data4.kw += x.data
    } else {
        data4.kw = data.kw.slice(0, -1)
    }
    clearTimeout(timer2)
    timer2 = setTimeout(() => {
        api.oederidList(data4).then((res) => {
            orderidList.value = res.data.data
        })
    }, 100)
}
/**copt to order 弹窗开始 */

// 右侧订单产品详情列表
const copydata = {
    token: token,
    order_id: ''
}
const leftOrder = ref([])
const getorderProductList = (ID) => {
    copydata.order_id = ID
    api.copyOrder(copydata).then((res) => {
        leftOrder.value = res.data.item
    })
}
// 左侧订单产品详情列表
const rightOrder = ref([])
// 复制到订单
const copyOrder = () => {
    rightOrder.value = selectList.value
}
// 保存
const copyOrderSave = (id) => {
    const cplist = rightOrder.value.map((item) => {
        return {
            "product_id": item.product_id, //产品ID
            "Brand_id": item.Brand_id, //品牌ID
            "Brand_name": item.Brand_name, //品牌名
            "product_name_pi": item.product_name_pi, //产品名（model）
            "quantity": item.quantity, //数量
            "price": item.price, //价格
            "leadingtime": item.leadingtime, //交期
            "product_condition": item.product_condition
        }
    })
    const cpdata = {
        token: token,
        order_id: '',
        item: cplist
    }
    cpdata.order_id = id
    api.orderSaveCopyToOrder(cpdata).then((res) => {
        if (res.Status === 0) {
            copy.value.orderID1 = ''
            copy.value.open = false
            leftOrder.value = []
            rightOrder.value = []
            ElMessage({
                type: 'success',
                message: 'Successful replication',
            })
        }
    })
}
// cp 新建订单
const newOrder = () => {
    copy.value.open = false
    publicNew(3, 0)

}

// copy to order 新建保存
const copyNeworderSave = () => {
    // 恢复默认编辑保存
    issave.value = 1
    publicNeworder(neworderList, copy, leftOrder, rightOrder)
}
/**copt to order 弹窗结束 */

/* *rfq qtn 保存参数的公用参数 */
let order = {}

/** from rfq 弹窗开始 */
const rfqidList = ref([])
// 获取rfqID列表
const getrfqid = (x) => {
    rfqidList.value.push({
        label: 'rfq201229',
        id: 201229
    })
}
// rfq下拉框失去焦点
const resrfqid = () => {
    console.log('清空')
}
// 获取rfq产品列表
const rfqdata = {
    token: store.token,
    inquiry_id: '',
    page: 1
}
const rfqProductList = ref([])
const getrfqProductList = (id) => {
    rfqdata.inquiry_id = id
    api.orderFromRfq(rfqdata).then((res) => {
        rfqProductList.value = res.data.list.data
        order = res.data.customer
    })
}
// add按钮方法
const rfqnewList = ref([])
const rfqAdd = () => {
    rfqnewList.value = selectList.value
}
// rfq保存按钮方法
const rfqSave = (id) => {
    publicSave(rfqnewList, fromrfq, rfqProductList, id)

}
// rfq 新建订单
const rfqnewOrder = () => {
    fromrfq.value.open = false
    publicNew(4, 0)
}

// rfq新建订单保存
const rfqneworderSave = () => {
    // 恢复默认编辑保存
    issave.value = 1
    publicNeworder(neworderList, fromrfq, rfqProductList, rfqnewList)
}
/** from rfq 弹窗结束 */

/**from qtn 开始 */
const qtnidList = ref([])
// 获取qtnid
const getqtnid = () => {
    qtnidList.value.push(
        {
            label: 'qtn183283',
            id: 183283
        }
    )
}
// 失去焦点重置输入框
const resqtnid = () => {
    console.log('清空')
}
// 获取qtn详情列表
const qtnProductList = ref([])
const qtndata = {
    token: store.token,
    inquiry_id: '',
    page: 1
}
const getqtnProductList = (id) => {
    qtndata.inquiry_id = id
    api.orderFromQtn(qtndata).then((res) => {
        qtnProductList.value = res.data.list.data
        order = res.data.customer
    })
}
// add 方法
const qtnnewList = ref([])
const qtnAdd = () => {
    qtnnewList.value = selectList.value
}
// qtn save
const qtnSave = (id) => {
    publicSave(qtnnewList, fromqtn, qtnProductList, id)
}
// qtn neworder
const qtnnewOrder = () => {
    fromqtn.value.open = false
    publicNew(5, 0)

}
// qtn save
const qtnneworderSave = () => {
    // 恢复默认编辑保存
    issave.value = 1
    publicNeworder(neworderList, fromqtn, qtnProductList, qtnnewList)
}
/**from qtn 结束 */


/**Clearance 开始 */
const clearList = ref([])
const currentList = ref([])
const totalAmount = ref('')
const declareAmount = ref()
// 获取clear列表
const getClearList = () => {
    const cleardata = {
        token: token,
        order_id: order_id.value
    }
    api.orderClearance(cleardata).then((res) => {
        clearList.value = res.data.list
        currentList.value = res.data.Current
        totalAmount.value = res.data.order_total
        declareAmount.value = res.data.declare_total.replace(/,/g, '') * 1
    })
}

// 获取范围内的随机清关价格
let isrelease = ref(0)
const getnumber = (x, Number) => {
    isrelease.value = 1
    let max = Number
    let min
    let numberTimer
    if (x === 'Value') {
        min = Number * 0.8
        let num = (Math.random() * (max - min) + min).toFixed(2)
        declareAmount.value = num * 1
    } else if (x === '<500') {
        min = 400
        let num = (Math.random() * (max - min) + min).toFixed(2)
        declareAmount.value = num * 1
    } else if (x === '<700') {
        min = 500
        let num = (Math.random() * (max - min) + min).toFixed(2)
        declareAmount.value = num * 1
    } else if (x === '<800') {
        min = 700
        let num = (Math.random() * (max - min) + min).toFixed(2)
        declareAmount.value = num * 1
    } else {
        clearTimeout(numberTimer)
        numberTimer = setTimeout(() => {
            declareAmount.value = (totalAmount.value.replace(/,/g, '') * 1) * (x / 100)
        }, 1000)
    }
}

// 清关订单保存
const ClearanceSave = () => {
    const invoice = clearList.value.map(item => {
        return {
            "order_info_id": item.order_info_id,
            "product_name_invoice": item.product_description_pi,
            "product_description_invoice": item.product_description_invoice,
            "price_declare_invoice": clearance.value.calculatePrice(totalAmount.value, item.price * 1)

        }
    })
    const clearData = {
        token: token,
        invoice: invoice
    }
    api.orderClearanceSave(clearData).then((res) => {
        isrelease.value = 0
        if (res.Status === 0) {
            clearance.value.open = false
            clearance.value.clearMoney = ''
            clearance.value.percentage = ''
            ElMessage({
                type: 'success',
                message: 'Save successfully',
            })
        }
    })
}
/**Clearance 结束 */

/***Expost PI开始 */
const imgList = ref([])
const exportPImodels = ref([])
const capitalTotal = ref({})
const invoiceInfo = ref({})
const getExportPI = () => {
    const exportData = {
        token: token,
        order_id: order_id.value
    }
    api.ordersClearanceData(exportData).then((res) => {

        imgList.value = res.data.logo && res.data.logo.map(item => {
            const imgUrl = 'http://test3.files99.com/static/images/logo/' + item
            return imgUrl
        })
        exportPImodels.value = res.data.item
        capitalTotal.value = res.data.total
        invoiceInfo.value = res.data.order
    })
}

/***Expost PI结束 */

/***Place an Order开始 **/
// 获取采购员列表
const buyerList = ref([])
const buyerdata = {
    token: token,
    kw: '',
    group: 2,
    page: 1
}
const getBuyerList = () => {
    api.ordersConfigGetUser(buyerdata).then((res) => {
        buyerList.value = res.data.data.map((item) => {
            item.id = item.id * 1
            return item
        })
    })
}
// Place an Order弹框顶部设置采购按钮
const changePur = (x) => {
    orderDetails.value.map(item => {
        item.purcharse = x.split('|')[1]
        item.purcharse1 = x.split('|')[0] * 1
        return item
    })

}
const changeRadio = (x) => {
    x == 2 ? orderDetails.value.map(item => {
        item.purcharse = ''
        item.purcharse1 = ''
        return item
    }) : ''
}
// 创建采购任务
const takeAdddata = {
    token: token,
    item: []
}
const purchaseOrderteskAdd = (allList, x) => {
    let item
    if (x == 1) {
        item = allList.map(item => {
            return {
                "order_info_id": item.order_info_id,
                "Purchaser_id": typeof (item.purcharse) == 'string' ? item.purcharse1 : item.purcharse,
                "quantity": item.quantity - item.hqty
            }
        })
    } else {
        item = allList.map(item => {
            return {
                "order_info_id": item.order_info_id,
                "Purchaser_id": item.purcharse,
                "quantity": item.pqty * 1
            }
        })
    }
    takeAdddata.item = item
    api.purchaseOrderteskAdd(takeAdddata).then((res) => {
        if (res.Status === 0) {
            placeanOrder.value.purcharse = ''
            placeanOrder.value.open = false
            ElMessage({
                type: 'success',
                message: 'Successful order',
            })
        }
    })
}
// 获取已订货数据
const orderedList = ref([])
const orderedData = {
    token: token,
    item_ids: []
}
const getOrderedList = () => {
    let item_ids = orderDetails.value.map((item) => {
        return {
            "order_info_id": item.order_info_id
        }
    })
    orderedData.item_ids = item_ids
    api.ordersPurchaseTesk(orderedData).then((res) => {
        orderedList.value = res.data
        orderDetails.value = orderDetails.value.map(item => {
            item.purcharse = '';
            item.purcharse1 = '';
            item.pqty = '';
            item.hqty = orderedList.value.filter((item1) => {
                return item.order_info_id == item1.order_info_id
            })[0].Qtynumber
            return item
        })
    })
}
/***Place an Order结束 **/

/**获取底部弹框子组件方法开始 */
const discount = ref()
const vat = ref()
const shippingCost = ref()
const paymentfee = ref()

// 底部弹框保存公共参数
const publicData = {
    token: token,
    order_id: '',
    type: '',
    fee: ''
}
let disTimer
/** Discount 弹框开始*/
const calculation = () => {
    clearTimeout(disTimer)
    disTimer = setTimeout(() => {
        let percentage = discount.value.ratio / 100
        discount.value.CalculatedNumber = (subTotal.value * percentage).toFixed(2)
    }, 1000);
}
// 保存数值
const discountSave = (type) => {
    publicData.order_id = order_id.value
    publicData.type = type
    publicData.fee = discount.value.CalculatedNumber * 1
    api.ordersServiceCharge(publicData).then((res) => {
        if (res.Status === 0) {
            discountInfo.value = discount.value.CalculatedNumber
            totalInfo.value = (discountInfo.value * 1) + (shippingCostInfo.value * 1) + (paymentFeeInfo.value * 1) + (vatInfo.value * 1)
            discount.value.open = false
            discount.value.ratio = ''
            discount.value.CalculatedNumber = ''
            ElMessage({
                type: 'success',
                message: 'Save successfully',
            })
        }
    })
}
/** Discount 弹框结束*/

/**shippingCost 弹框开始 */
const shippingCostSave = (type) => {
    publicData.order_id = order_id.value
    publicData.type = type
    publicData.fee = shippingCost.value.ShippingCost * 1
    api.ordersServiceCharge(publicData).then((res) => {
        if (res.Status === 0) {
            shippingCostInfo.value = shippingCost.value.ShippingCost
            totalInfo.value = (discountInfo.value * 1) + (shippingCostInfo.value * 1) + (paymentFeeInfo.value * 1) + (vatInfo.value * 1)
            shippingCost.value.open = false
            shippingCost.value.ShippingCost = ''
            ElMessage({
                type: 'success',
                message: 'Save successfully',
            })
        }
    })
}
/**shippingCost 弹框结束 */

/**Vat 弹框开始 */
const vatcalculation = () => {
    clearTimeout(disTimer)
    disTimer = setTimeout(() => {
        let percentage = vat.value.ratio / 100
        vat.value.CalculatedNumber = (subTotal.value * percentage).toFixed(2)
    }, 1000);
}
// 保存
const vatSave = (type) => {
    publicData.order_id = order_id.value
    publicData.type = type
    publicData.fee = vat.value.CalculatedNumber * 1
    api.ordersServiceCharge(publicData).then((res) => {
        if (res.Status === 0) {
            vatInfo.value = vat.value.CalculatedNumber
            totalInfo.value = (discountInfo.value * 1) + (shippingCostInfo.value * 1) + (paymentFeeInfo.value * 1) + (vatInfo.value * 1)
            vat.value.open = false
            vat.value.ratio = ''
            vat.value.CalculatedNumber = ''
            ElMessage({
                type: 'success',
                message: 'Save successfully',
            })
        }
    })
}
/**Vat 弹框结束 */


/**PaymentFee 弹框开始 */
const paymentFeecompute = () => {
    paymentfee.value.CalculatedNumber = (subTotal.value * paymentfee.value.ratio).toFixed(2)
}
const paymentFeeSave = (type) => {
    publicData.order_id = order_id.value
    publicData.type = type
    publicData.fee = paymentfee.value.CalculatedNumber * 1
    api.ordersServiceCharge(publicData).then((res) => {
        if (res.Status === 0) {
            paymentFeeInfo.value = paymentfee.value.CalculatedNumber
            totalInfo.value = (discountInfo.value * 1) + (shippingCostInfo.value * 1) + (paymentFeeInfo.value * 1) + (vatInfo.value * 1)
            paymentfee.value.open = false
            paymentfee.value.CalculatedNumber = ''
            ElMessage({
                type: 'success',
                message: 'Save successfully',
            })
        }
    })
}
/**PaymentFee 弹框结束 */

// 开启底部弹框
const open1 = (x) => {
    if (x === 1) {
        console.log(utils.currencType('USD'))
        discount.value.dialogopen()
    }
    else if (x === 2) {
        shippingCost.value.dialogopen()
    }
    else if (x === 3) {
        paymentfee.value.dialogopen()
    }
    else if (x === 4) {
        vat.value.dialogopen()
    }
}
/**获取底部弹框子组件方法结束 */
/********************************销售单逻辑结束******************************************** */



/********************************采购单逻辑开始******************************************** */
/*** 获取采购任务开始**/
const purcharseTakeList = ref([])
const purTitle = ref('')
const purTime = ref('')
const takedata = {
    token: token,
    page: ''
}
const getpurTakeList = () => {
    takedata.page = 1
    api.purchaseOrderTakeList(takedata).then((res) => {
        purcharseTakeList.value = res.data.data.map((item) => {
            item.State = utils.fstate(item.State)
            return item
        })
        getPurTake1()
    })
}
// 上拉加载
const refreshPurTakeList = () => {
    takedata.page++
    api.purchaseOrderTakeList(takedata).then((res) => {
        purcharseTakeList.value = [
            ...purcharseTakeList.value,
            ...res.data.data.map((item) => {
                item.State = utils.fstate(item.State)
                return item
            })
        ]
    })

}

// 获取任务详情
const takeDetailList = ref([])
let purchaseordertesk_id = ''
let purchaserPeople = ''
const takeDetaildata = {
    token: token,
    purchaseordertesk_id: ''
}
//点击
const getPurTake = (row) => {
    if (allocationState.value) {
        return false
    }
    takeDetaildata.purchaseordertesk_id = row.purchaseordertesk_id
    purchaseordertesk_id = row.purchaseordertesk_id
    purchaserPeople = row.purchaser
    purTitle.value = row.PI_name
    purTime.value = row.create_time
    takeDetails()
}
// 默认
const getPurTake1 = () => {
    takeDetaildata.purchaseordertesk_id = purcharseTakeList.value[0].purchaseordertesk_id
    purchaseordertesk_id = purcharseTakeList.value[0].purchaseordertesk_id
    purchaserPeople = purcharseTakeList.value[0].purchaser
    purTitle.value = purcharseTakeList.value[0].PI_name
    purTime.value = purcharseTakeList.value[0].create_time
    takeDetails()
}
const takeDetails = () => {
    api.purchaseOrderteskDetail(takeDetaildata).then((res) => {
        takeDetailList.value = res.data.list.data.map(item => {
            item.use_number = 3
            // 分配采购id
            item.purchaser = purchaserPeople
            // 走库房数
            item.WarehouseNumber = item.use_number > item.Qtynumber ? item.Qtynumber : item.use_number,
                // 存放更改后的id
                item.purcharse = '';
            // 分配采购数量
            item.quantity = '';
            // 创建采购单的采购数量
            item.Pquantity = ((item.Qtynumber * 1) - (item.use_number * 1) < 0) ? 0 : (item.Qtynumber * 1) - (item.use_number * 1);
            // 创建采购单的采购价
            item.Pmoney = ''
            // 利润
            item.Profits = ''
            // 总价
            item.Total = ''
            return item
        })
    })
}
/***获取采购任务结束**/

/***分配任务开始 **/
const allocationState = ref(false)
const atdata = {
    token: token,
    Purchaseordertesk_id: '',
    item: []
}
const allocationMethod = (val) => {
    if (val === 'AssignTasks') {
        allocationState.value = true
        getBuyerList()
    } else {
        //分配保存放这里做
        let item = takeDetailList.value.map((item) => {
            return {
                "Purchaseordertesk_detailed_id": item.Purchaseordertesk_detailed_id,
                "Purchaser_id": item.purcharse,
                "quantity": item.quantity,
                "order_info_id": item.order_info_id
            }
        })
        atdata.item = item
        atdata.Purchaseordertesk_id = purchaseordertesk_id
        api.purchaseOrderteskReassign(atdata).then((res) => {
            if (res.Status == 0) {
                ElMessage({
                    type: 'success',
                    message: 'Successful deployment',
                })
                // 计算调配后的qty
                takeDetailList.value = takeDetailList.value.map((item) => {
                    item.Qtynumber = item.Qtynumber - item.quantity,
                        item.quantity = '',
                        item.purcharse = ''
                    return item
                })
                allocationState.value = false
            }
        })

    }

}
// 分配数量判断
let comparetimer
const compare = (row) => {
    clearTimeout(comparetimer)
    comparetimer = setTimeout(() => {
        if ((row.Qtynumber * 1 - row.quantity * 1) < 0) {
            ElMessage({
                type: 'info',
                message: 'Insufficient allocation',
            })
            takeDetailList.value = takeDetailList.value.map(item => {
                item.quantity = ''
                return item
            })
        }
    }, 1000)
}


/***分配任务结束 **/

/***退回采购任务开始 **/
const renturndata = {
    token: token,
    Purchaseordertesk_detailed_id: ''
}
const returnTask = (Purchaseordertesk_detailed_id) => {
    renturndata.Purchaseordertesk_detailed_id = Purchaseordertesk_detailed_id
    api.purchaseOrderteskCallbackOrder(renturndata).then((res) => {
        if (res.Status == 0) {
            ElMessage({
                type: 'success',
                message: 'Successful return',
            })
        }
    })
}
/***退回采购任务结束 **/
/***删除采购任务开始 **/
const taskdeldata = {
    token: token,
    Purchaseordertesk_id: ''
}
const taskDelete = () => {
    taskdeldata.Purchaseordertesk_id = purchaseordertesk_id
    ElMessageBox.confirm(
        'Are you sure to delete this purchase order?',
        'Warning',
        {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            distinguishCancelAndClose: true,
        }
    )
        .then(() => {
            api.purchaseOrderteskDelete(taskdeldata).then((res) => {
                if (res.Status == 0) {
                    ElMessage({
                        type: 'success',
                        message: 'Deleted successfully',
                    })
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete cancel',
            })
        })

}
/***删除采购任务结束 **/

/***创建采购单开始 **/
const newPurchaseOrder = ref()
const openNewOrder = () => {
    getPsupplierList()
    newPurchaseOrder.value.dialogopen()
}
// 获取供应商列表
const pSupplierList = ref([])
const getPsupplierList = () => {
    userdata.is_supplier = 1
    api.orderUser(userdata).then((res) => {
        pSupplierList.value = res.data.data
    })
}

// 数量输入方法，主要计算总价和判断输入的值是否大于任务数
let inputPqtyTimer
const inputPqty = (NonStock) => {
    clearTimeout(inputPqtyTimer)
    inputPqtyTimer = setTimeout(() => {
        takeDetailList.value = takeDetailList.value.map(item => {
            if (!NonStock && item.Pquantity > item.Qtynumber - item.use_number) {
                ElMessage({
                    type: 'info',
                    message: 'Insufficient allocation',
                })
                item.Pquantity = (item.Qtynumber * 1) - (item.use_number * 1)
            } else if (NonStock && item.Pquantity > item.Qtynumber) {

                ElMessage({
                    type: 'info',
                    message: 'Insufficient allocation',
                })
                item.Pquantity = item.Qtynumber * 1

            }
            // 总价
            item.Total = item.Pmoney * item.Pquantity
            return item
        })
    }, 500)
}
// 价格输入框主要实现计算总价和利润
let inPmoneyTimer
const inPmoney = () => {
    clearTimeout(inPmoneyTimer)
    inPmoneyTimer = setTimeout(() => {
        takeDetailList.value = takeDetailList.value.map(item => {
            // 总价
            item.Total = item.Pmoney * item.Pquantity
            // 利润
            item.Profits = ((((item.Price * 1) - (item.Pmoney * 1)) / (item.Pmoney * 1)) * 100).toFixed(2)
            return item
        })
    }, 500)
}
// 创建订单点击事件
const cpoData = {
    token: token,
    order_id: '123345',
    customer_info_id: '',
    item: []
}
/**
 * 
 * @param {*是否库存} NonStock 
 * @param {*供应商Id} pSupplierID 
 * 
 */
const CreatePurchaseOrder = (NonStock, pSupplierID) => {
    cpoData.customer_info_id = pSupplierID
    let items = []
    items = takeDetailList.value.map((item) => {
        if (NonStock) {
            return {
                'Purchaseordertesk_detailed_id': item.Purchaseordertesk_detailed_id,
                'products_id': item.products_id,
                'Qtynumber': item.Pquantity * 1,
                'Purchase_price': item.Pmoney,
                'Profit': item.Profits,
                'lead': item.lead,
                'is_stock': 0
            }
        } else {
            if (item.Qtynumber > item.use_number && item.use_number > 0) {
                return [{
                    'Purchaseordertesk_detailed_id': item.Purchaseordertesk_detailed_id,
                    'products_id': item.products_id,
                    'Qtynumber': item.use_number,
                    'Purchase_price': item.Pmoney,
                    'Profit': item.Profits,
                    'lead': item.lead,
                    'is_stock': 1
                }, {
                    'Purchaseordertesk_detailed_id': item.Purchaseordertesk_detailed_id,
                    'products_id': item.products_id,
                    'Qtynumber': item.Pquantity * 1,
                    'Purchase_price': item.Pmoney,
                    'Profit': item.Profits,
                    'lead': item.lead,
                    'is_stock': 0
                }]
            }
            else if (item.Qtynumber < item.use_number || item.Qtynumber == item.use_number) {
                return {
                    'Purchaseordertesk_detailed_id': item.Purchaseordertesk_detailed_id,
                    'products_id': item.products_id,
                    'Qtynumber': item.Qtynumber,
                    'Purchase_price': item.Pmoney,
                    'Profit': item.Profits,
                    'lead': item.lead,
                    'is_stock': 1
                }
            }
            else {
                return {
                    'Purchaseordertesk_detailed_id': item.Purchaseordertesk_detailed_id,
                    'products_id': item.products_id,
                    'Qtynumber': item.Pquantity * 1,
                    'Purchase_price': item.Pmoney,
                    'Profit': item.Profits,
                    'lead': item.lead,
                    'is_stock': 0
                }
            }
        }
    })
    let itemList = []
    items.forEach((item) => {
        if (Array.isArray(item)) {
            item.forEach((item1) => {
                itemList.push(item1)
            })
        } else {
            itemList.push(item)
        }
    })
    cpoData.item = itemList
    api.purchaseOrderAdd(cpoData).then((res) => {
        if (res.Status == 0) {
            newPurchaseOrder.value.open = false
            ElMessage({
                type: 'success',
                message: 'Add successfully',
            })
            getPurchaseOrderList()
        }
    })
}

//非库存改变值时触发
const changeNonStock = (NonStock) => {
    takeDetailList.value = takeDetailList.value.map(item => {
        if (NonStock) {
            // 这里点击不走库存后，直接将输入框赋值为任务数量
            item.Pquantity = item.Qtynumber

        } else {
            // 这里判断输入的数量如果任务数量小于库房数，则输入数量为0，否则就按计算值赋值给输入框
            item.Pquantity = (item.Qtynumber * 1) - (item.use_number * 1) < 0 ? 0 : (item.Qtynumber * 1) - (item.use_number * 1);
        }
        return item
    })


}
/***创建采购单结束 **/


/***获取采购单开始**/
const purorderdata = {
    token: token,
    page: ''
}
// 采购单ID

const purchaseOrderDetailList = ref([])
const getPurchaseOrderList = () => {
    purorderdata.page = 1
    api.purchaseOrderList(purorderdata).then((res) => {
        purchaseOrderDetailList.value = res.data.data.map((item) => {
            item.firstname = item.firstname.slice(0, 5)
            return item
        })
        getPurchaseOrderListDetail()
    })
}
const getPurchaseOrderList1 = () => {
    purorderdata.page++
    api.purchaseOrderList(purorderdata).then((res) => {
        purchaseOrderDetailList.value = [
            ...purchaseOrderDetailList.value,
            ...res.data.data.map((item) => {
                item.firstname = item.firstname.slice(0, 4)
                return item
            })
        ]

    })
}
// 获取采购单详情
const porderData = {
    token: token,
    Purchaseorder_id: '',
    page: 1
}
const purchaseorder_id = ref('')
const purOrderDetailList = ref([])
//默认
const getPurchaseOrderListDetail = () => {
    purchaseorder_id.value = purchaseOrderDetailList.value[0].purchaseorder_id * 1
    porderData.Purchaseorder_id = purchaseOrderDetailList.value[0].purchaseorder_id
    purOrderDetail()
}
// 点击
const getPurOrderID = (row) => {
    purchaseorder_id.value = row.purchaseorder_id * 1
    porderData.Purchaseorder_id = row.purchaseorder_id
    purOrderDetail()
}
const purOrderDetail = () => {
    api.purchaseOrderDetailed(porderData).then((res) => {
        purOrderDetailList.value = res.data.data
    })
}
/***获取采购单结束**/

/*** 导出采购单开始**/
 const exportPurOrder = ref()
const ExportPorder = () => {
    exportPurOrder.value.dialogopen()

}
/*** 导出采购单结束**/
/********************************采购单逻辑结束******************************************** */
onMounted(() => {
    store.type == 2 || store.type == 4 ? getOrderList() : '';
    store.type == 3 || store.type == 0 ? getpurTakeList() : '';
    store.type == 3 || store.type == 0 ? getPurchaseOrderList() : '';
    getleading();
    getCondition();
    confirmPermission()

})
</script>
<style lang="less" scoped>
@import url(./order.less);
</style>